package com.situ.ymall.service.impl;

import com.situ.ymall.entity.User;
import com.situ.ymall.mapper.UserMapper;
import com.situ.ymall.service.UserService;
import com.situ.ymall.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 1-创建service层的接口
 * 2-声明方法
 * 3-创建service层的实现类，添加@service注解
 * 4-实现service层的方法，使用Autowired注入mapper层对象
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public int reg(User user, String rePassword) {
        // 1- 验证输入格式
        if(user.getUsername().length() < 3 || user.getUsername().length() > 16){
            return -1;
        }
        if(user.getPassword().length() < 3 || user.getPassword().length() > 16){
            return -2;
        }
        // 2- 比较两次密码是否一致
        if(user.getPassword().length() == 0  || rePassword.length() == 0){
                return -5;
        }
        if (!rePassword.equals(user.getPassword())){
            return -3;
        }
        // 3- 判断账号是否可用
        User selectUser = userMapper.selectByUserName(user.getUsername());
        if (selectUser != null){
            return -4;
        }
        // 4- 写入数据库
        user.setPassword(MD5Util.getMD5(rePassword));

        return userMapper.insert(user);
    }

    @Override
    public User login(User user) throws Exception {
        // 1.验证格式是否正确
        if (user.getUsername().length() < 3 || user.getUsername().length() > 16){
            throw new Exception("账号格式不对");
        }
        //验证密码格式
        if (user.getPassword().length() < 3 || user.getPassword().length() > 16){
            throw new Exception("密码格式不对");
        }
        User selectUser = userMapper.selectByUserName(user.getUsername());
        //验证账户
        if (selectUser == null){
            throw new Exception("账号不存在");
        }
        //验证密码
        if ( ! MD5Util.getMD5(user.getPassword()).equals(selectUser.getPassword()) ){
            throw new Exception("密码不正确");
        }
        //验证用户的状态
        if (selectUser.getStatus() == 1){
            throw new Exception("账号已被禁用，请联系管理员");
        }
        return selectUser;
    }
}
